package com.imooc.ad.mysql;

import com.alibaba.fastjson.JSON;
import com.imooc.ad.mysql.constant.OpType;
import com.imooc.ad.mysql.dto.ParseTemplate;
import com.imooc.ad.mysql.dto.TableTemplate;
import com.imooc.ad.mysql.dto.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 加载配置文件并解析，实现列索引到列名映射
 */
@Slf4j
@Component
public class TemplateHolder {

    //sql语句查询列索引和列名关系
    private String SQL_SCHEMA = "select table_schema, table_name, " +
            "column_name, ordinal_position from information_schema.columns " +
            "where table_schema = ? and table_name = ?";

    private ParseTemplate template;
    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public TemplateHolder(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //加载到SpringIOC容器时立即执行
    @PostConstruct
    private void init() {
        loadJson("template.json");
    }

    //对外实现方法，根据表名获取表属性TableTemplate
    public TableTemplate getTable(String tableName) {
        return template.getTableTemplateMap().get(tableName);
    }

    //加载配置文件
    private void loadJson(String path) {

        //根据路径，获取当前线程的输入流
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        InputStream inStream = cl.getResourceAsStream(path);

        try {
            //将模板文件中json信息，进行反序列化
            Template template = JSON.parseObject(inStream, Charset.defaultCharset(), Template.class);
            //解析模板文件
            this.template = ParseTemplate.parse(template);
            //列索引和列名映射
            loadMeta();
        } catch (IOException ex) {
            //模板文件template.json不存在
            log.error(ex.getMessage());
            throw new RuntimeException("fail to parse json file");
        }
    }

    //实现每张表的列索引到列名的映射
    private void loadMeta() {

        //获取所有的tableTemplateMap对象
        Set<Map.Entry<String, TableTemplate>> entrys = template.getTableTemplateMap().entrySet();

        //遍历包含了tableTemplateMap对象的集合
        for (Map.Entry<String, TableTemplate> entry : entrys) {

            //获取tableTemplateMap的value值，即每张表的属性TableTemplate
            TableTemplate table = entry.getValue();

            //获取每种操作类型对应的列
            List<String> insertFields = table.getOpTypeFieldSetMap().get(OpType.ADD);
            List<String> updateFields = table.getOpTypeFieldSetMap().get(OpType.UPDATE);
            List<String> deleteFields = table.getOpTypeFieldSetMap().get(OpType.DELETE);

            //查询列索引和列名关系
            jdbcTemplate.query(SQL_SCHEMA,
                    new Object[]{template.getDatabase(), table.getTableName()}, (rs, i) -> {

                //获取列索引和列名
                int pos = rs.getInt("ORDINAL_POSITION");
                String colName = rs.getString("COLUMN_NAME");

                //判断该字段colName是否存在，且是否包含在对应操作类型的opTypeFieldSetMap中
                if ((insertFields != null && insertFields.contains(colName))
                        || (updateFields != null && updateFields.contains(colName))
                        || (deleteFields != null && deleteFields.contains(colName))) {

                    //TableTemplate中字段索引-1和字段名关系
                    table.getPosMap().put(pos - 1, colName);
                }
                return null;
            });
        }
    }
}
